package cat

import (
	"context"
	"wzgames/internal/app"
	"wzgames/internal/gloader"
	"wzgames/internal/services"
	"wzgames/internal/services/cat"
	"wzgames/pkg/actor/actorservice"
	"wzgames/pkg/server/rpcx"
)

func RunServer() error {
	bootc := gloader.BootConfig()
	return app.Start(bootc,
		app.BeforeStart(func(ctx context.Context) error {
			err := gloader.CommMgr().LoadSysConfig()
			if err == nil {
				err = gloader.CommMgr().LoadSysCurrencies(true)
			}
			if err == nil {
				err = gloader.CommMgr().LoadSysMaintain(true)
			}
			return gloader.CommMgr().WatchCommConfig()
		}, func(ctx context.Context) error {
			err := gloader.GameMgr().LoadSysGame(true)
			if err == nil {
				err = gloader.GameMgr().LoadAgents(true)
			}
			return gloader.GameMgr().WatchBasePath()
		}, func(ctx context.Context) error {
			err := gloader.CommMgr().InitWdb()
			if err == nil {
				err = gloader.CommMgr().InitRedis()
			}
			if err == nil {
				err = gloader.CommMgr().StartIdWorker()
			}
			if err == nil {
				err = gloader.InitSonyFlakeID()
			}
			if err != nil {
				return err
			}

			rpcx.RegisterService(services.RPCxServiceCat, cat.NewCatService(), "")
			return actorservice.StartService(cat.Actor())
		}),
		app.Server(rpcx.NewRPCx(bootc.Node().RpcConf)),
		app.AfterStart(func(ctx context.Context) error {
			gloader.GameMgr().ListenChange()
			return nil
		}),
		app.AfterStop(func(ctx context.Context) error {
			cat.Actor().OnDestroy()
			gloader.Res().Stop()
			return nil
		}),
	)
}
